﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using AzureTracer.ViewModels;

namespace AzureTracer.Views.Converters
{
    public class HighlightSearchConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string originalText = value.ToString();
            string hightlightText = ViewModelLocator.Main.SearchText; // esto deberia ser el campo parameter, pero no se puede utilizar un binding
            var inlines = new List<Inline>();

            if (string.IsNullOrWhiteSpace(hightlightText))
                inlines.Add(new Run() { Text = originalText });
            else
            {
                int charIndex = 0;
                var splitText = originalText.ToLowerInvariant().Split(new string[] { hightlightText }, StringSplitOptions.None);

                for (int i = 0; i < splitText.Length; i++)
                {
                    if (splitText[i] == string.Empty) continue;

                    if (i != 0)
                    {
                        string highlightRealPiece = originalText.Substring(charIndex, hightlightText.Length);
                        inlines.Add(
                        new Run()
                        {
                            Text = highlightRealPiece,
                            FontWeight = FontWeights.Bold
                        });
                        charIndex += highlightRealPiece.Length;
                    }

                    string realTextPiece = originalText.Substring(charIndex, splitText[i].Length);
                    inlines.Add(
                        new Run()
                        {
                            Text = realTextPiece,
                            FontStyle = FontStyles.Normal
                        });

                    charIndex += splitText[i].Length;
                }
            }
            return inlines;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
